package main

import (
	"io"
	"os"
	"path/filepath"

	"github.com/lab-online/config"
	app "github.com/lab-online/internal"
	"github.com/lab-online/pkg/database"
	"github.com/lab-online/pkg/logger"
	"github.com/lab-online/pkg/util"
	"github.com/spf13/pflag"
	"gorm.io/gorm"
)

func main() {
	db := database.ConnectDB(config.Service.Postgres, &gorm.Config{})

	server := &app.Context{DB: db}

	if err := server.Migrate(); err != nil {
		logger.Error("migrate database failed")
		panic(err)
	}

	logger.Info("migrate database success")

	setupInitialData(db)
}

func setupInitialData(db *gorm.DB) {
	pwd, _ := os.Getwd()
	initialFile := filepath.Join(pwd, pflag.Lookup("initial").Value.String())

	initialData, err := os.OpenFile(initialFile, os.O_RDONLY, 0644)
	if err != nil {
		logger.Error("open initial file failed")
		panic(err)
	}

	defer initialData.Close()
	logger.Info("using initial file", initialFile)

	if dataBytes, err := io.ReadAll(initialData); err != nil {
		logger.Error("read initial file failed")
		panic(err)
	} else if data, err := util.UnmarshalJSON[Initial](dataBytes); err != nil {
		logger.Error("unmarshal initial data failed")
		panic(err)
	} else {
		setupCourse(db, data)
		setupUser(db, data)
	}
}
